package com.leo.client;

import com.alibaba.fastjson.JSON;
import com.leo.model.Message;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Date;

/**
 * @ClassName FXChatClient
 * @Description
 * @Author wangss
 * @date 2021.11.26 21:12
 * @Version 1.0
 */
public class FXChatClient2 extends WebSocketClient {

    public FXChatClient2(URI serverUri) {
        super(serverUri);
    }

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        System.out.println("client onOpen success");
    }

    @Override
    public void onMessage(String msg) {
        System.out.println("客户端接收到的信息 : " + msg);
        Message message = new Message("ztt", "wangss", "我知道了", new Date());
        this.send(JSON.toJSONString(message));
    }

    @Override
    public void onClose(int i, String s, boolean b) {
        System.out.println("client onClose success");
    }

    @Override
    public void onError(Exception e) {
        System.out.println("client onError success");
    }

    public static void main(String[] args) throws URISyntaxException, InterruptedException {
        String url = "ws://localhost:8887/ztt";
        FXChatClient2 fxChatClient = new FXChatClient2(new URI(url));
        // 链接
        fxChatClient.connect();
        while (!fxChatClient.getReadyState().equals(ReadyState.OPEN)) {
            System.out.println("连接还没有打开");
            Thread.sleep(1000);
        }
        System.out.println("连接已经建立");
    }
}
